package tech.xs.common.file.client.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import tech.xs.common.file.client.AbstractFileClient;
import tech.xs.common.file.client.domain.properties.FileClientMinioProperties;
import tech.xs.common.file.client.domain.properties.FileClientProperties;
import tech.xs.sdk.minio.MinioSdk;
import tech.xs.sdk.minio.domain.enums.MinioReadWriteAuthEnums;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.InputStream;

/**
 * @author 沈家文
 * @since 2023/6/29 15:49
 */
@Slf4j
@Configuration
@EnableConfigurationProperties
@ConditionalOnProperty(value = "file-client.type", havingValue = "minio")
public class MinioFileClient extends AbstractFileClient {
    private MinioSdk sdk;

    private String bucketName;

    @Resource
    private FileClientProperties properties;

    @PostConstruct
    public void init() {
        log.info("开始初始化Minio文件中心");
        FileClientMinioProperties minioConfig = properties.getMinio();
        if (!minioConfig.getIsAutoCreateBucket()) {
            log.info("文件中心无需初始化");
            return;
        }
        bucketName = minioConfig.getBucketName();
        try {
            sdk = new MinioSdk(minioConfig);
            if (!sdk.isExistBucket(bucketName)) {
                sdk.createBucket(bucketName, MinioReadWriteAuthEnums.publicRead);
            } else {
                sdk.setBucketAuth(bucketName, MinioReadWriteAuthEnums.publicRead);
            }
        } catch (Exception e) {
            log.error("文件中心初始化失败", e);
        }
    }

    @Override
    public String upload(String filePath, InputStream stream) {
        log.info("文件上传 filePath:" + filePath);
        sdk.upload(bucketName, filePath, stream);
        return filePath;
    }

    @Override
    public void delete(String path) {
        sdk.delete(bucketName, path);
    }

    @Override
    public InputStream download(String path) {
        return sdk.download(bucketName, path);
    }

}
